<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { onMounted, ref } from 'vue'
import type { MsgTable } from '@/types/msg'
import { sendMsg } from '@/api/msg'
import { authXSS, deepCopy } from '@/util/token'
import Editor from '@/components/Editor.vue'
const props = defineProps<{
  dMap: Map<string, string>
  data?: MsgTable
  // 刷新
  refresh: () => void
}>()
// 关闭
const emit = defineEmits<{
  (event: 'cDlg'): void
}>()
const addForm = ref<MsgTable>({
  msg: '',
  type: 'text',
  title: ''
})
if (props.data) {
  addForm.value = deepCopy(props.data)
}
const formRules = ref<FormRules<MsgTable>>({
  title: [
    {
      required: true,
      message: '请输入公告标题'
    }
  ],
  msg: [
    {
      required: true,
      message: '请输入公告类容'
    }
  ]
})
const editorRef = ref<{
  save: () => string
  setContent: (data: string) => void
}>()

onMounted(() => {
  editorRef.value?.setContent(authXSS(props.data?.msg || ''))
})
// 表单dom
const elFormRef = ref<FormInstance>()
function add() {
  addForm.value.msg = editorRef.value?.save()
  elFormRef.value?.validate((d) => {
    if (d) {
      sendMsg(addForm.value)
        .then((d) => {
          ElMessage.success(d.msg)
          emit('cDlg')
          props.refresh()
        })
        .catch((d) => {
          ElMessage.error(d.msg)
        })
    }
  })
}
</script>

<template>
  <el-scrollbar height="65vh">
    <el-form ref="elFormRef" :model="addForm" :rules="formRules" label-width="90px">
      <el-form-item required :label="(dMap.get('title') || 'title') + '：'" prop="title">
        <el-input
          v-model="addForm.title"
          :placeholder="'请输入' + dMap.get('title') || 'title'"
        ></el-input>
      </el-form-item>
      <el-form-item required :label="(dMap.get('msg') || 'msg') + '：'" prop="msg">
        <Editor ref="editorRef"></Editor>
      </el-form-item>
    </el-form>
  </el-scrollbar>
  <div class="buttons">
    <el-button type="primary" @click="emit('cDlg')">取消</el-button>
    <el-button type="success" @click="add">发送</el-button>
  </div>
</template>
<style scoped lang="less">
.buttons {
  display: flex;
  margin-top: 30px;
  justify-content: flex-end;
}
</style>
